package com.huihe.framework.config;

import com.huihe.framework.config.serializer.FastJson2JsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Spring Data Redis 的配置类
 */
@Configuration
public class RedisConfig {

    /**
     * 配置 RedisTemplate,使用 RedisTemplate 与 Redis 数据库进行交互
     * @param connectionFactory 负责创建与 Redis 数据库的连接。在application.yml配置中决定使用哪个
     * @return RedisTemplate的Bean
     */
    @Bean
    @Primary
    @SuppressWarnings(value = {"rawtypes"})
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置Redis连接
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer fastJson2JsonRedisSerializer = new FastJson2JsonRedisSerializer<>(Object.class);

        // 使用StringRedisSerializer来 序列化 和 反序列化 redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(fastJson2JsonRedisSerializer);

        // Hash的key也采用StringRedisSerializer的 序列化 方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(fastJson2JsonRedisSerializer);

        // 使用前必须的调用,确保RedisTemplate被正确配置和初始化
        template.afterPropertiesSet();
        return template;
    }
}
